SYSSIZE     equ 0x3000
SETUPLEN    equ 4
BOOTSEG     equ 0x07c0
INITSEG     equ 0x9000
SETUPSEG    equ 0x9020
SYSSEG      equ 0x1000
ENDSEG      equ SYSSEG + SYSSIZE

start:
    mov ax, BOOTSEG
    mov ds, ax
    mov ax, INITSEG
    mov es, ax
    mov cx, 256
    sub si, si
    sub di, di
    rep
    movsw           ; 将bootsect.s从0x7c00移动到0x90000
    jmp INITSEG:go
go: mov ax, cs
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0xff00

load_setup:
    mov dx, 0x00
    mov cx, 0x02
    mov bx, 0x0200
    mov ax, 0x0200 + SETUPLEN
    int 0x13        ; 加载setup.s到0x90200
    jnc ok_load_setup
    mov dx, 0x00
    mov ax, 0x00
    int 0x13
    jmp load_setup  ; 加载失败则复位软盘，重新加载

ok_load_setup:
    mov dl, 0x00
    mov ax, 0x0800
    int 0x13        ; 获取每磁道扇区数
    mov ch, 0x00
    mov [sectors], cx
    mov ax, INITSEG
    mov es, ax

    mov ah, 0x03
    xor bh, bh
    int 0x10        ; 获取光标位置

    mov cx, 24
    mov bx, 0x0007
    mov bp, msg
    mov ax, 0x1301
    int 0x10        ; 打印字符串

    mov ax, SYSSEG
    mov es, ax
    call    read_it
    call    kill_motor

    jmp SETUPSEG:0  ; 跳转到setup.s的内容

read_it:
    mov ax, es
    test    ax, 0x0fff
die:jne     die
    xor bx, bx
rp_read:
    mov ax, es
    cmp ax, ENDSEG
    jb  ok1_read
    ret
ok1_read:
    mov ax, [sectors]
    sub ax, [sread]
    mov cx, ax
    shl cx, 9
    add cx, bx
    jnc ok2_read
    je  ok2_read
    xor ax, ax
    sub ax, bx
    shr ax, 9
ok2_read:
    call    read_track
    mov cx, ax
    add ax, [sread]
    cmp ax, [sectors]
    jne ok3_read
    mov ax, 1
    sub ax, [head]
    jne ok4_read
    push ax
    mov ax, [track]
    inc ax
    mov [track], ax
    pop ax
ok4_read:
    mov [head], ax
    xor ax, ax
ok3_read:
    mov [sread], ax
    shl cx, 9
    add bx, cx
    jnc rp_read
    mov ax, es
    add ax, 0x1000
    mov es, ax
    xor bx, bx
    jmp rp_read

read_track:
    push    ax
    push    bx
    push    cx
    push    dx
    mov dx, [track]
    mov cx, [sread]
    inc cx          ; 要读取的扇区号等于已读的扇区数加1
    mov ch, dl
    mov dx, [head]
    mov dh, dl
    mov dl, 0x00
    and dx, 0x0100  ; 磁头号不大于1
    mov ah, 2
    int 0x13
    jc  bad_rt
    pop dx
    pop cx
    pop bx
    pop ax
    ret
bad_rt:
    mov ax, 0
    mov dx, 0x00
    int 0x13
    pop dx
    pop cx
    pop bx
    pop ax
    jmp read_track

kill_motor:
    push    dx
    mov dx, 0x3f2
    mov al, 0
    out dx, al
    pop dx
    ret

sread:
    dw  1 + SETUPLEN
head:
    dw  0
track:
    dw  0
sectors:
    dw  0

msg:
    db 13, 10
    db "Loading system ..."
    db 13, 10, 13, 10

    times 0x1fe - ($ - $$) db 0 ; 填写0，直到0x1fe
    dw 0xaa55       ; 启动盘标识
